'use strict';

const DBConn = require('../lib/dbconn');

const BLOGVERSION = Symbol('Application#BLOGVERSION');
const NAMESPACE = Symbol('Application#NAMESPACE');
const CACHECLEANCODE = Symbol('Application#CACHECLEANCODE');
const CONN = Symbol('Application#CONN');

let cacheState = {};

module.exports = {

  get blogVersion() {
    if (!this[BLOGVERSION]) {
      this[BLOGVERSION] = '2.0.313';
    }
    return this[BLOGVERSION];
  },

  get lbsNamespace() {
    if (!this[NAMESPACE]) {
      this[NAMESPACE] = 'lbs01_';
    }
    return this[NAMESPACE];
  },

  // Define the code which is used to trigger cache cleaning
  // Use "?cleancache=%YOUR CODE HERE%" to trigger
  // Modify this to prevent other people clean your cache
  get cacheCleanCode() {
    if (!this[CACHECLEANCODE]) {
      this[CACHECLEANCODE] = 'doit';
    }
    return this[CACHECLEANCODE];
  },

  get connBlog() {
    if (!this[CONN]) {
      this[CONN] = new DBConn(this);
    }
    return this[CONN];
  },

  /**
   * 缓存操作
   * @param {{undefined|String}} key 为字符串代表键名；不传意味着返回所有缓存
   * @param {{undefined|Object}} value
   * @return {*}
   */
  cache(key, value) {
    if (cacheState[this.lbsNamespace] === undefined) {
      cacheState[this.lbsNamespace] = {};
    }

    if (key === undefined) { // 返回有所值
      return cacheState[this.lbsNamespace];
    }

    if (key === null) { // 清除所有值
      cacheState[this.lbsNamespace] = {};
      return true;
    }

    if (value === undefined) { // 取指定值
      return cacheState[this.lbsNamespace][key];
    }

    if (value === null) { // 清除指定键
      delete cacheState[this.lbsNamespace][key];
      return true;
    }

    // 赋值
    cacheState[this.lbsNamespace][key] = value;
    return true;
  },
};
